package com.base.commonlib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;

import com.base.commonlib.R;

import java.util.List;

/**
 * Created by arvin on 2018/8/17.
 */

public class MineSpinner extends android.support.v7.widget.AppCompatSpinner {
    private Context mContext;
    public ArrayAdapter mAdapter;
    private List<Object> mData;
    private final String mTitle;

    public MineSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.spinner_title);
        mTitle = typedArray.getString(R.styleable.spinner_title_title);
        typedArray.recycle();
    }


    public <T>void init(List<T> data) {
        mData = (List<Object>) data;
        mAdapter = new ArrayAdapter<>(mContext, R.layout.spinner_item, R.id.tv_spinner, data);
        mAdapter.setDropDownViewResource(R.layout.spinner_dropdown_iitem);
        this.setAdapter(mAdapter);

    }


    @Override
    public void setSelection(int position) {
        boolean same = position == getSelectedItemPosition();
        super.setSelection(position);
        if (same) {
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }


    @Override
    public void setSelection(int position, boolean animate) {
        boolean same = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (same) {
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public boolean performClick() {
        new SingleChooseDialog<Object>(mContext, mTitle, mData, new SingleChooseDialog.OnItemChooseListener() {
            @Override
            public void onItemChoose(Object o) {
                setSelection(mData.indexOf(o));
            }
        }).show();
        return true;

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
}
